<script setup>
import {useRoute, useRouter} from 'vue-router'
import {reactive, ref} from "vue";
import {deleted, get, post} from "@/utils/request.js";
import {showNotify} from "vant";
import {parseMonth, parseDay} from "@/utils/DateUtil.js";
import dayjs from "dayjs";

const router = useRouter();
const route = useRoute()

const nameParam = route.query.name;
const categoryeParam = route.query.category;
const activeTabeParam = route.query.activeTab;
const searchDateParam = route.query.searchDate;
let data = reactive({
  processData: [],

  search: "",
  dates: [],
  homeStatisticsData: {},
  purchaser: "",
  settlement: false,
  defaultDates: []
})

const toAddProcess = () => {
  router.push("/addProcess")
}
const loading = ref(false);


const show = ref(false);
data.dates = []

console.log(activeTabeParam, searchDateParam)
if (activeTabeParam === '月统计') {
  const year = searchDateParam[0];
  const month = searchDateParam[1];
  const d = dayjs(`${year}-${month}`, 'YYYY-MM');
  let begind = d.startOf("month")
  const endDate = d.endOf("month")
  while (begind.isBefore(endDate)) {
    data.dates.push(begind.format("YYYY-MM-DD"));
    data.defaultDates.push(begind.toDate())
    begind = begind.add(1, "day");
    console.log(begind)
  }
}
if (activeTabeParam === '年统计') {
  const year = searchDateParam[0];
  const d = dayjs(`${year}`, 'YYYY');
  let begind = d.startOf("year")
  const endDate = d.endOf("year")
  while (begind.isBefore(endDate)) {
    data.dates.push(begind.format("YYYY-MM-DD"));
    data.defaultDates.push(begind.toDate())
    begind = begind.add(1, "day");
    console.log(begind)
  }
}

if (categoryeParam != null) {
  data.purchaser = nameParam;
}


const onSearch = () => {
  post("/api/process/list", {
    dates: data.dates,
    key: data.search,
    "purchaser": data.purchaser,
    settlement: data.settlement ? 1 : 0
  }).then((res) => {
    data.processData = res.data;
    loading.value = false
  })
}
onSearch()

const formatDate = (date) => {
  return `${date.getFullYear()}-${parseMonth(date.getMonth())}-${parseDay(date.getDate())}`;
};

const onConfirm = (values) => {
  show.value = false;
  data.dates = values.map(item => {
    console.log(formatDate(item));

    return formatDate(item);
  })

  onSearch()
};

const updateRecordClick = (id) => {
  router.push({name: 'addProcess', query: {id: id}})
}
const onRemove = (id) => {
  deleted('/api/process/removeById/' + id)
      .then(res => {
        showNotify("删除成功");
        onRefresh()
      })
}

const toAddProcessDetail = (id) => {
  router.push({name: 'addProcessDetail', query: {id: id}})
}

const toProcessDetail = (id) => {
  router.push({name: 'processDetail', query: {id: id}})
}

const loadingRefresh = ref(false);

// 下拉刷新
const onRefresh = () => {
  onSearch()
  loadingRefresh.value = false
  get("/api/process/homeStatistics")
      .then((res) => {
        data.homeStatisticsData = res.data;
      })
};
get("/api/process/homeStatistics")
    .then((res) => {
      data.homeStatisticsData = res.data;
    })

function toStatistics() {
  router.push("/processStatistics")
}

const showPurchasersPicker = ref(false);
let purchasersColumn = [{text: '全部', value: 'all'}]
get("/api/book/listPurchaser")
    .then(res => {
      data.purchasers = res.data;
      for (const item of res.data) {
        purchasersColumn.push({
          text: item,
          value: item,
        })
      }
    });

const onPurchaseConfirm = ({selectedValues}) => {
  data.purchaser = selectedValues.join(',')
  if (data.purchaser === 'all') {
    data.purchaser = "";
  }
  showPurchasersPicker.value = false;
  onSearch()
};

const settlementChange = () => {
  onSearch();
}

</script>

<template>
  <div id="process-home">
    <div class="title">
      <van-nav-bar>
        <template #left>
          <h3>加工</h3>
        </template>
      </van-nav-bar>
    </div>
    <div class="tongji" @click="toStatistics">
      <h3 style="text-align: center">统计</h3>
    </div>
    <div class="addBtn">
      <van-button type="primary" block @click="toAddProcess">
        新增记录
      </van-button>
    </div>
    <div class="searchBtn" style="text-align: right;margin-right: 8px;margin-top: 11px;">
      <van-search v-model="data.search" placeholder="请输入搜索关键词" @search="onSearch">
        <template #left>
          <van-button plain icon="calendar-o" hairline color="#000000" size="small" @click="show = true">
            日期
          </van-button>
        </template>
      </van-search>
      <div>
        <van-field
            v-model="data.purchaser"
            is-link
            readonly
            @click="showPurchasersPicker = true"
            label="采购商"
            placeholder="选择采购商"
        >采购商
        </van-field>
      </div>
      <van-checkbox v-model="data.settlement" @change="settlementChange">是否查看已结算</van-checkbox>
    </div>
    <div class="records">
      <van-pull-refresh v-model="loadingRefresh" @refresh="onRefresh">
        <div v-for="itemMap  in data.processData">
          <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
            {{ itemMap[0].bookDate }}
          </van-divider>
          <van-swipe-cell v-for="item in itemMap">

            <van-card
                :num="item.weight"
                :desc="'工艺:'+item.craft"
                :title="item.productName"
                @click="updateRecordClick(item.id)"
            >
              <template #tags>
                <van-tag plain type="primary">采购商:{{ item.purchaser }}</van-tag>
                <van-tag plain type="primary">经办人:{{ item.director }}</van-tag>
              </template>
              <template #price>
                <van-space :size="20">
                  <van-button
                      :type="item.recordType==='未开票'?'danger':''"
                      :plain="item.recordType!=='未开票'"
                      :hairline="item.recordType!=='未开票'"
                      size="mini">{{ item.recordType }}
                  </van-button>
                  <van-button
                      type="danger"
                      v-if="item.detailIsNotInvoiced"
                      size="mini">归还未开票
                  </van-button>
                  <span>
                {{ item.bookDate }}
               </span>
                </van-space>
              </template>
              <template #num>
            <span>
             <div>
                拉:{{ item.weight }}KG
             </div>
              <div>
                  <span>
                送:{{ item.residualWeight }}KG
              </span>
              </div>

            </span>
              </template>
              <template #footer>
                <van-button
                    hairline
                    type="primary"
                    @click.stop="updateRecordClick(item.id)"
                    size="small">编辑
                </van-button>
              </template>
            </van-card>
            <template #right>
              <van-button square text="删除" type="danger" class="delete-button" @click="onRemove(item.id)"/>
            </template>
          </van-swipe-cell>
        </div>
      </van-pull-refresh>
    </div>
    <div class="extra">
      <van-calendar
          v-model:show="show"
          type="multiple"
          switch-mode="year-month"
          @close="show = false"
          :default-date="data.defaultDates"
          @confirm="onConfirm"/>
      <van-popup v-model:show="showPurchasersPicker" round position="bottom">
        <van-picker
            :columns="purchasersColumn"
            @cancel="showPurchasersPicker = false"
            @confirm="onPurchaseConfirm"
        />
      </van-popup>
    </div>
  </div>

</template>

<style scoped>
.tongji {
  background-color: rgba(221, 239, 241, 1);
  margin: 8px;
  padding: 8px 0px;
}

.delete-button {
  height: 100%;
}

.tongji .left > div {
  margin-top: 5px;
  margin-left: 1px;
}

.tongji {

}

.red {
  color: red;
}
</style>